package com.jzg.jcptadmin.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.CommonUtil;
import com.jzg.jcptadmin.Utils.InputLowerToUpper;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyNumberKeyListener;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.adpter.FastOnLineStatusAdapter;
import com.jzg.jcptadmin.adpter.HistoricalPriceAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.CheckVinBean;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.CheckVinPrsenter;
import com.jzg.jcptadmin.presenter.OperationPresenter;
import com.jzg.jcptadmin.presenter.TaskDetailPresenter;
import com.jzg.jcptadmin.view.FullyGridLayoutManager;
import com.jzg.jcptadmin.viewinterface.CheckVinAccidentInterface;
import com.jzg.jcptadmin.viewinterface.OperationInterface;
import com.jzg.jcptadmin.viewinterface.TaskDetailInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 评估师6张  第三方机构鉴定结果列表详情
 */
public class TaskDetailActivity extends BaseActivity implements TaskDetailInterface, OperationInterface,CheckVinAccidentInterface {
    @Bind(R.id.rvContent)
    RecyclerView rvContent;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @Bind(R.id.tvVinCode)
    TextView tvVinCode;
    @Bind(R.id.tvCurrEvluation)
    TextView tvCurrEvluation;
    @Bind(R.id.tvHistoryEvluation)
    TextView tvHistoryEvluation;
    @Bind(R.id.etBuyPrice)
    EditText etBuyPrice;
    @Bind(R.id.etSoldPrice)
    EditText etSoldPrice;
    @Bind(R.id.etDetectResult)
    EditText etDetectResult;
    @Bind(R.id.llCurr)
    LinearLayout llCurr;
    @Bind(R.id.lvHistory)
    ListView lvHistory;
    @Bind(R.id.llHistory)
    LinearLayout llHistory;
    @Bind(R.id.et_tuihui)
    EditText etTuihui;
    @Bind(R.id.ll_tuihui)
    LinearLayout llTuihui;
    @Bind(R.id.appraiseDes)
    TextView appraiseDes;
    @Bind(R.id.price_pinggu)
    TextView pricePinggu;
    @Bind(R.id.ll_pinggu)
    LinearLayout llPinggu;
    @Bind(R.id.price_pingguc2b)
    TextView pricePingguc2b;
    @Bind(R.id.ll_c2b)
    LinearLayout llC2b;
    @Bind(R.id.price_pinggub2c)
    TextView pricePinggub2c;
    @Bind(R.id.ll_b2c)
    LinearLayout llB2c;
    @Bind(R.id.price_linear)
    LinearLayout priceLinear;
    @Bind(R.id.isshowPrice)
    LinearLayout isshowPrice;
    @Bind(R.id.tv_commit)
    TextView tvCommit;
    @Bind(R.id.ll_ll_history)
    LinearLayout llGuzhi;
    @Bind(R.id.iv_dengji)
    ImageView ivDengji;
    @Bind(R.id.et_VinCode)
    EditText etVinCode;
    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.tv_right)
    TextView tvRight;


    private boolean showCurr = true;

    private String vinCode;
    private User user;
    private CarDetails carDetails;
    private TaskDetailPresenter taskDetailPresenter;
    public StatusData.ItemListEntity.FastOnLineBtnEntity status;
    private PopupWindow pwMyPopWindow;
    private ListView lvPopupList;
    private FastOnLineStatusAdapter fastOnLineStatusAdapter;
    private List<String> statusList;
    private OperationPresenter operationPresenter;
    private CheckVinPrsenter checkVinPresenter;
    private List<String> listpic = new ArrayList<>();//小图
    private List<String> titlePic = new ArrayList<>();//小图注释
    private List<String> listpicBig = new ArrayList<>();//大图
    private boolean isPinggu = false;
    private String titleStr;
    private String orderStatus; //订单状态
    private String isAccident; // 是否是事故车辆

    @BindString( R.string.accident_tip )
    String accidentTip;

    /**
     * 手机app检测系统：
     * 1、app退回原因跳转到新界面
     * 2、任务查看改派任务需要做
     * 3、行驶本默认图片、行驶证占位图片
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);
        ButterKnife.bind(this);
        status = appContext.getStatus().getItemList().getFastOnLineBtn();
        taskDetailPresenter = new TaskDetailPresenter(DataManager.getInstance());
        taskDetailPresenter.attachView(this);
        // ToastDialog();
        operationPresenter = new OperationPresenter(DataManager.getInstance());
        operationPresenter.attachView(this);
        checkVinPresenter = new CheckVinPrsenter(DataManager.getInstance());
        checkVinPresenter.attachView(this);
        user = appContext.getUser();
        carDetails = getIntent().getParcelableExtra("carDetails");

        titleStr = getIntent().getStringExtra("title");
        initVin();
        if (carDetails != null) {
            initView();
        } else {
            Toast.makeText(TaskDetailActivity.this, "获取详情失败", Toast.LENGTH_SHORT).show();
            finish();
        }
        orderStatus = getIntent().getStringExtra(Constant.ORDER_STATUS);
        isAccident = getIntent().getStringExtra(Constant.VIN_STATE);
        iniPopupWindow();
        checkVinState();
    }

    private void ToastDialog() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ("1".equals(carDetails.getAlreadyValuation())) {
                            CommonUtil.showSingleChoiceDialog(TaskDetailActivity.this, Constant.VIN_REPETITION);
                        }
                    }
                });
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    private void initVin() {
        etVinCode.setKeyListener(new MyNumberKeyListener());
        etVinCode.setTransformationMethod(new InputLowerToUpper());
    }


    /**
     * 检查当前Vin是否在黑名单列表里
     */
    private void checkVinState(){
        //先检查是不是事故车辆
        if (!(("1").equals(isAccident) && !TextUtils.isEmpty(orderStatus) && orderStatus.compareTo("2") < 0 )) { //事故车辆，并且订单状态是未评估
            ToastDialog();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showVinWarningDialog();
                    }
                });

            }
        }).start();
    }

    private void showVinWarningDialog(){
        SweetAlertDialog alertDialog = new SweetAlertDialog(TaskDetailActivity.this);
        alertDialog.setTitleText(accidentTip);
        alertDialog.setContentText("    ");
        alertDialog.setConfirmText("知道了");
        alertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                ToastDialog();
            }
        });
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    //
    private void initView() {
        if (!TextUtils.isEmpty(carDetails.getProductTypeImage())) {
            ivDengji.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(carDetails.getProductTypeImage(), ivDengji, appContext.options);
        } else {
            ivDengji.setVisibility(View.GONE);
        }
//        aaaa(etTuihui);
        StringUtils.priceTextWatcher(etBuyPrice, appContext);
        StringUtils.priceTextWatcher(etSoldPrice, appContext);
        ViewGroup.LayoutParams params = convenientBanner.getLayoutParams();
        params.width = RadioGroup.LayoutParams.MATCH_PARENT;
        params.height = ScreenUtils.getScreenWidth(this) * 9 / 16;
        convenientBanner.setLayoutParams(params);
//        if (TextUtils.isEmpty(carDetails.getIconUrl())) {
//            ivDengji.setVisibility(View.GONE);
//            ImageLoader.getInstance().displayImage(carDetails.getIconUrl(), ivDengji, appContext.options);
//        } else {
//            ivDengji.setVisibility(View.VISIBLE);
//        }
        titleContent.setText("任务查看");//TODO 根据不同的角色显示不同的标题
        statusList = new ArrayList<>();
        //获取操作的筛选条件
        initOperation();
        if (statusList.size() <= 0) {
            tvRight.setVisibility(View.GONE);
        } else {
            tvRight.setVisibility(View.VISIBLE);
            tvRight.setText("操作");
        }
        int length = carDetails.getCarPicList().size();

//        tvVinCode.setText(carDetails.getVin());
        etVinCode.setText(carDetails.getVin());
        etVinCode.setSelection(etVinCode.length());//光标到最后一行

        initHistoricalPrice();//初始化历史估值

        for (int i = 0; i < carDetails.getCarPicList().size(); i++) {
            listpic.add(carDetails.getCarPicList().get(i).getPath());
            int tag = i + 1;
            titlePic.add(carDetails.getCarPicList().get(i).getItemName() + "(" + tag + "/" + length + ")");
            listpicBig.add(carDetails.getCarPicList().get(i).getPathBig());
        }
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, listpic);
//        convenientBanner.startTurning(5000);
        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {//查看大图
                Intent intent = new Intent(TaskDetailActivity.this, GalleryActivity.class);
                intent.putExtra(ActivityHelp.KEY_POSITION, position);
                intent.putExtra(ActivityHelp.KEY_IMG_URLS, (ArrayList) listpicBig);
                startActivity(intent);
            }
        });
        setPicAdapter();
        if (isPinggu) {   //可以提交评估价格
            etVinCode.setFocusable(true);
            etVinCode.setEnabled(true);
            llGuzhi.setVisibility(View.VISIBLE);   //c2b车商收车价
//            String strB2C = StringUtils.getPrice(carDetails.getSalePriceB2C());//车商售车价
//            String strC2B = StringUtils.getPrice(carDetails.getSalePriceC2B());//车商收车价

            etBuyPrice.setText(StringUtils.getPrice1(carDetails.getSalePriceC2B()));//车商收车价
            etSoldPrice.setText(StringUtils.getPrice1(carDetails.getSalePriceB2C()));//车商售车价
            etDetectResult.setText(carDetails.getAppraiseDes());
            isshowPrice.setVisibility(View.GONE);
            llTuihui.setVisibility(View.GONE);
        } else if (carDetails.getOperation().equals("1")) {//显示退回原因
            etVinCode.setFocusable(false);
            etVinCode.setEnabled(false);
            llTuihui.setVisibility(View.VISIBLE);
            etTuihui.setText(carDetails.getTaskBack());

            llGuzhi.setVisibility(View.GONE);
            isshowPrice.setVisibility(View.GONE);
        } else if (carDetails.getOperation().equals("2")) {  // 显示2个价格
            etVinCode.setFocusable(false);
            etVinCode.setEnabled(false);
            try {
                llTuihui.setVisibility(View.GONE);
                llGuzhi.setVisibility(View.GONE);
                isshowPrice.setVisibility(View.VISIBLE);
                String strB2C = carDetails.getSalePriceB2C();//车商售车价
                String strC2B = carDetails.getSalePriceC2B();//车商收车价
                BigDecimal bdB2C = new BigDecimal(Double.parseDouble(strB2C));
                BigDecimal bdC2B = new BigDecimal(Double.parseDouble(strC2B));
                llPinggu.setVisibility(View.GONE);
                llB2c.setVisibility(View.VISIBLE);
                llC2b.setVisibility(View.VISIBLE);
                DecimalFormat fnum = new DecimalFormat("##0.00");
                pricePinggub2c.setText(fnum.format(bdB2C) + "万元");
                pricePingguc2b.setText(fnum.format(bdC2B) + "万元");
                appraiseDes.setText(carDetails.getAppraiseDes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (carDetails.getOperation().equals("3")) {  //3 显示一个价钱
            etVinCode.setFocusable(false);
            etVinCode.setEnabled(false);
            try {
                llTuihui.setVisibility(View.GONE);
                llGuzhi.setVisibility(View.GONE);
                isshowPrice.setVisibility(View.VISIBLE);
                llPinggu.setVisibility(View.VISIBLE);
                llB2c.setVisibility(View.GONE);
                llC2b.setVisibility(View.GONE);
                String str = carDetails.getAppraise();
                BigDecimal bd = new BigDecimal(Double.parseDouble(str));
                pricePinggu.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
                appraiseDes.setText(carDetails.getAppraiseDes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (carDetails.getOperation().equals("4")) { //全部不显示
            etVinCode.setFocusable(false);
            etVinCode.setEnabled(false);
            llTuihui.setVisibility(View.GONE);
            llGuzhi.setVisibility(View.GONE);
            isshowPrice.setVisibility(View.GONE);
        }
//        if(!TextUtils.isEmpty(carDetails.getTaskBack())){
//            llTuihui.setVisibility(View.VISIBLE);
//            llGuzhi.setVisibility(View.GONE);
//            isshowPrice.setVisibility(View.GONE);
//        }else{
//            llTuihui.setVisibility(View.GONE);
//        }
//
//        try {
//            if (carDetails.getIsShowPrice().equals("0")) {
//                isshowPrice.setVisibility(View.GONE);
//            } else {
//                isshowPrice.setVisibility(View.VISIBLE);
//                if (user.getIsDL().equals("1")) {  //1是第三方机构  显示一个价格
//                    llPinggu.setVisibility(View.VISIBLE);
//                    llB2c.setVisibility(View.GONE);
//                    llC2b.setVisibility(View.GONE);
//                    String str = carDetails.getAppraise();
//                    BigDecimal bd = new BigDecimal(Double.parseDouble(str));
//                    pricePinggu.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
//                } else {  //显示两个价格
//                    String strB2C = carDetails.getSalePriceB2C();//车商售车价
//                    String strC2B = carDetails.getSalePriceC2B();//车商收车价
//                    BigDecimal bdB2C = new BigDecimal(Double.parseDouble(strB2C));
//                    BigDecimal bdC2B = new BigDecimal(Double.parseDouble(strC2B));
//                    llPinggu.setVisibility(View.GONE);
//                    llB2c.setVisibility(View.VISIBLE);
//                    llC2b.setVisibility(View.VISIBLE);
//                    pricePinggub2c.setText(bdB2C.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
//                    pricePingguc2b.setText(bdC2B.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
//                }
//            }
//    } catch (Exception e) {
//        e.printStackTrace();
//    }

    }

//    private void aaaa(final EditText editText) {
//        editText.setOnKeyListener(new EditText.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                // TODO Auto-generated method stub
//                String temp = editText.getText().toString();
//                editText.setText("");
//                editText.append(ToSBC(temp));
//                return false;
//            }
//        });
//    }


    private void initHistoricalPrice() {
        ViewGroup.LayoutParams params = lvHistory.getLayoutParams();
        params.width = RadioGroup.LayoutParams.MATCH_PARENT;
        params.height = ScreenUtils.getScreenWidth(this) * 3 / 4;
        //params.height = RadioGroup.LayoutParams.WRAP_CONTENT;
        lvHistory.setLayoutParams(params);
        List<CarDetails.TaskListData> listData = carDetails.getHistoryTaskList();
        if (listData != null) {
            if (listData.size() == 0) {
                CarDetails.TaskListData taskListData = new CarDetails.TaskListData();
                taskListData.setHAppraiserName("--");
                taskListData.setHCityName("--");
                taskListData.setHDateTime("--");
                taskListData.setB2CPrice("--");
                taskListData.setC2BPrice("--");
//                taskListData.setHPrice("收321"+"\n"+"售345");
                listData.add(taskListData);
            }
            HistoricalPriceAdapter historicalPriceAdapter = new HistoricalPriceAdapter(listData, appContext);
            lvHistory.setAdapter(historicalPriceAdapter);
        } else {
            List<CarDetails.TaskListData> listData1 = new ArrayList<>();
            CarDetails.TaskListData taskListData = new CarDetails.TaskListData();
            taskListData.setHAppraiserName("--");
            taskListData.setHCityName("--");
            taskListData.setHDateTime("--");
            taskListData.setB2CPrice("--");
            taskListData.setC2BPrice("--");
//            taskListData.setHPrice("收321"+"\n"+"售345");
            listData1.add(taskListData);
            HistoricalPriceAdapter historicalPriceAdapter = new HistoricalPriceAdapter(listData1, appContext);
            lvHistory.setAdapter(historicalPriceAdapter);
        }
    }

    private void initOperation() {
        String[] strs = carDetails.getButtonStr().split(",");
        List<StatusData.ItemListEntity.FastOnLineBtnEntity.ItemEntity> itemEntityList = status.getItem();
        for (int i = 0; i < itemEntityList.size(); i++) {
            for (int j = 0; j < strs.length; j++) {
                if (itemEntityList.get(i).getId().equals(strs[j])) {
                    if (!strs[j].equals("5")) {//服务器显示评估但不显示
                        statusList.add(itemEntityList.get(i).getValue());
                    } else {
                        isPinggu = true;
                    }
                }
            }
        }
    }

    private void setPicAdapter() {
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(this, 2);
        rvContent.setLayoutManager(gridLayoutManager);
        rvContent.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        rvContent.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL));
        rvContent.setAdapter(new InfoRVAdapter());
    }

    @Override
    public void checkVinSucc(CheckVinBean suc) {
        if ("1".equals(suc.getIsAccident())){
            dismissDialog();
            String title = "";
//            String content = "该vin码已有事故车记录";
            String confirmText = "返回修改";
            String cancelText = "继续提交";
            SweetAlertDialog sweetDialog = new SweetAlertDialog(TaskDetailActivity.this);
            SweetAlertDialog.OnSweetClickListener confirmListener = new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();

                }
            };
            SweetAlertDialog.OnSweetClickListener cancelListener = new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                    showDialog();
                    taskDetailPresenter.UpData();
                }
            };

            if (!TextUtils.isEmpty(title)) {
                sweetDialog.setTitleText(title);
            }
            if (!TextUtils.isEmpty(accidentTip)) {
                sweetDialog.setContentText(accidentTip);
            }
            if (!TextUtils.isEmpty(confirmText)) {
                sweetDialog.setConfirmText(confirmText);

                    sweetDialog.setConfirmClickListener(confirmListener);
            }
            if (!TextUtils.isEmpty(cancelText)) {
                sweetDialog.setCancelText(cancelText);
                sweetDialog.setCancelClickListener(cancelListener);
            }
            sweetDialog.show();

        }else{
            taskDetailPresenter.UpData();
        }
    }

    @Override
    public void checkVinFail(String fail) {
        taskDetailPresenter.UpData();
    }

    @Override
    public Map<String, String> getcheckVinParams() {
//        Vin=LH17CKKFXAH144371&UserId=3
        Map<String, String> params = new HashMap<String, String>();
        params.put("UserId", "3");
        params.put("tokenid", "6");
        params.put("Vin", etVinCode.getText().toString().trim().toUpperCase());
//        params.put("Vin", "LH17CKKFXAH144371");
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));

        return params;
    }


    class InfoRVAdapter extends RecyclerView.Adapter<InfoRVAdapter.MyHolder> {
        String itemNames[] = {"品牌车系", "排量", "变速器", "驱动方式", "初登日期", "下单地区", "评估编号", "机构名称"};
        //        String datas[] = {"本田Civic", "1.8L", "自动", "两驱", "2016-4-28", "北京", "BJPG9823J23Y243R23G", "易鑫方案一"};
        String datas[] = {carDetails.getModelName(), carDetails.getEngine_Exhaust().trim(), carDetails.getTransmissionType().trim(),
                carDetails.getPerf_DriveType().trim(), carDetails.getRegDateYear() + "-" + carDetails.getRegDateMonth(),
                carDetails.getProvinceName() + " " + carDetails.getCityName(), carDetails.getOrderNo(), carDetails.getSourceName()};

        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_car_info, parent, false);
            return new MyHolder(v);
        }

        @Override
        public void onBindViewHolder(MyHolder holder, int position) {
            holder.tvIndex.setText(itemNames[position]);
            if (position == 7) {
                if ("1".equals(carDetails.getShowSourceName())) {
                    holder.tvContent.setText(datas[position]);
                } else {
                    holder.tvContent.setText("暂不提供");
                }
            } else {
                holder.tvContent.setText(datas[position]);
            }

        }

        @Override
        public int getItemCount() {
            return itemNames.length;
        }

        class MyHolder extends RecyclerView.ViewHolder {
            TextView tvIndex;
            TextView tvContent;

            public MyHolder(View itemView) {
                super(itemView);
                tvIndex = (TextView) itemView.findViewById(R.id.tvIndex);
                tvContent = (TextView) itemView.findViewById(R.id.tvContent);
            }
        }
    }

    private void iniPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        if (fastOnLineStatusAdapter == null) {
            fastOnLineStatusAdapter = new FastOnLineStatusAdapter(appContext, statusList);
        }
        lvPopupList.setAdapter(fastOnLineStatusAdapter);
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                //点击操作回调,筛选操作的功能
                ScreenOperation(statusList.get(position));
                pwMyPopWindow.dismiss();


            }
        });

        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
        /*pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * NUM_OF_VISIBLE_LIST_ROWS);*/
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * (statusList.size() + 1));
        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
                R.drawable.bg_tanchu));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
    }

    public void ScreenOperation(String string) {

        switch (string) {
            case "退回":
                Intent intent4 = new Intent(this, RejectActivity.class);
                intent4.putExtra("id", carDetails.getCarId());
                intent4.putExtra("status", "退回");
                startActivity(intent4);
                break;
            case "改派":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要改派这条数据？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                showDialog();
                                operationPresenter.OperationData("gaipai", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
                                sDialog.dismissWithAnimation();
                            }
                        }).show();

                break;
            case "重发":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要重发这条数据？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                showDialog();
                                operationPresenter.OperationData("chongfa", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
                                sDialog.dismissWithAnimation();
                            }
                        }).show();

                break;
            case "删除":

                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要删除这条数据吗？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                showDialog();
                                operationPresenter.OperationData("del", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "审核通过":
//                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("提示")
//                        .setContentText("您确定要通过这条数据？")
//                        .setConfirmText("是的").setCancelText("取消")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sDialog) {
//                                showDialog();
//                                operationPresenter.OperationData("shenhe", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
//                                sDialog.dismissWithAnimation();
//                            }
//                        }).show();
                break;
            case "恢复":
                showDialog();
                operationPresenter.OperationData("huifu", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要恢复这条数据？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                showDialog();
                                operationPresenter.OperationData("huifu", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "签收":

//                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("提示")
//                        .setContentText("您确定要通过这条数据？")
//                        .setConfirmText("是的").setCancelText("取消")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sDialog) {
//                                showDialog();
//                                operationPresenter.OperationData("qianshou", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
//                                sDialog.dismissWithAnimation();
//                            }
//                        }).show();

                break;
            case "审核驳回":
//                Intent intent3 = new Intent(this, RejectActivity.class);
//                intent3.putExtra("id", carDetails.getCarId());
//                intent3.putExtra("status", "审核驳回");
//                startActivity(intent3);
                break;
            case "签收驳回":
//                Intent intent5 = new Intent(this, RejectActivity.class);
//                intent5.putExtra("id", carDetails.getCarId());
//                intent5.putExtra("status", "签收驳回");
//                startActivity(intent5);
                break;
            case "转到线下":
//                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("提示")
//                        .setContentText("您确定要将这条数据转到线下？")
//                        .setConfirmText("是的").setCancelText("取消")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sDialog) {
//                                showDialog();
//                                operationPresenter.OperationData("zhuanxianxia", carDetails.getCarId(), "", "", "", String.valueOf(appContext.getUser().getUserId()));
//                                sDialog.dismissWithAnimation();
//                            }
//                        }).show();
                break;
//            case "修改":
//                Intent intent6 = new Intent(this, QuickTaskModifyActivity.class);
//                intent6.putExtra("carDetails", carDetails);
//                startActivity(intent6);
//                break;

            default:

                break;
        }
    }

    @Override
    public void goBack(View v) {
        super.goBack(v);
    }


    private void refreshResult(TextView view, String result) {
        view.setText(result);
    }

    public boolean checkParams() {
        if (etVinCode.getText().toString().length() < 17) {
            Toast.makeText(this, "请输入正确的VIN", Toast.LENGTH_SHORT).show();
            return false;
        }
        String buyprice = etBuyPrice.getText().toString().trim();
        String soldprice = etSoldPrice.getText().toString().trim();
        if (TextUtils.isEmpty(buyprice)) {
            Toast.makeText(TaskDetailActivity.this, "收车价不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(soldprice)) {
            Toast.makeText(TaskDetailActivity.this, "售车价不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(etDetectResult.getText().toString().trim())) {
            Toast.makeText(TaskDetailActivity.this, "鉴定结果不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            Double prices = Double.parseDouble(buyprice);
            if (prices < 0.01) {
                Toast.makeText(TaskDetailActivity.this, "车商收车价不能小于0.01", Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (Exception e) {
            Toast.makeText(TaskDetailActivity.this, "车商收车价格错误", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            Double prices = Double.parseDouble(soldprice);
            if (prices < 0.01) {
                Toast.makeText(TaskDetailActivity.this, "车商售车价不能小于0.01", Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (Exception e) {
            Toast.makeText(TaskDetailActivity.this, "车商售价格错误", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    public Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("OP", "Simple");
        params.put("tokenid", "6");
        params.put("type", "pinggu");
        params.put("taskid", carDetails.getCarId());
        params.put("userId", appContext.getUser().getUserId() + "");
        params.put("appraiseprice", etBuyPrice.getText().toString());//收车价
        params.put("SalePrice", etSoldPrice.getText().toString());//售车价
        params.put("appraisedes", etDetectResult.getText().toString());
        params.put("VIN", etVinCode.getText().toString().trim().toUpperCase());
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));

        return params;
    }

    @Override
    public void showError(String error) {
        dismissDialog();
        Toast.makeText(this, "联网失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showData(SuccessData successData) {
        dismissDialog();
        if (successData.getStatus() == 100) {
            AppManager.getAppManager().finishActivity(KuaiSuOnLineActivity.class);
            Intent intent = new Intent(TaskDetailActivity.this, KuaiSuOnLineActivity.class);
            startActivity(intent);
            finish();
            Toast.makeText(TaskDetailActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(TaskDetailActivity.this, "提交失败" + successData.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    //操作的回调
    @Override
    public void showresult(SuccessData result) {
        dismissDialog();
        if (result.getStatus() == 100) {
            //操作成功
            ActivityHelp.startActivity(TaskDetailActivity.this, KuaiSuOnLineActivity.class);
            finish();

        } else {
            Toast.makeText(TaskDetailActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick({R.id.tvCurrEvluation, R.id.tvHistoryEvluation, R.id.tv_commit, R.id.iv_dengji, R.id.tv_right})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.tvCurrEvluation:
                if (showCurr)
                    return;
                else {
                    llCurr.setVisibility(View.VISIBLE);
                    llHistory.setVisibility(View.GONE);
                    lvHistory.setVisibility(View.GONE);
                    tvCurrEvluation.setBackgroundColor(getResources().getColor(R.color.btn_blue));
                    tvHistoryEvluation.setBackgroundColor(Color.WHITE);
                    tvCurrEvluation.setTextColor(Color.WHITE);
                    tvHistoryEvluation.setTextColor(getResources().getColor(R.color.btn_blue));
                    showCurr = !showCurr;
                }

                break;
            case R.id.tvHistoryEvluation:
                if (!showCurr)
                    return;
                else {
                    llCurr.setVisibility(View.GONE);
                    llHistory.setVisibility(View.VISIBLE);
                    lvHistory.setVisibility(View.VISIBLE);
                    tvCurrEvluation.setBackgroundColor(Color.WHITE);
                    tvHistoryEvluation.setBackgroundColor(getResources().getColor(R.color.btn_blue));
                    tvCurrEvluation.setTextColor(getResources().getColor(R.color.btn_blue));
                    tvHistoryEvluation.setTextColor(Color.WHITE);
                    showCurr = !showCurr;
                }
                break;
            case R.id.tv_commit: //提交
                if (checkParams()) {
                    showDialog();
                    checkVin();
                    //taskDetailPresenter.UpData();
                }
                break;
//            case R.id.iv_dengji:
//                List icons = new ArrayList();
//                icons.add(carDetails.getIconUrl());
//                intent = new Intent(TaskDetailActivity.this, GalleryActivity.class);
//                intent.putExtra(ActivityHelp.KEY_POSITION, 0);
//                intent.putExtra(ActivityHelp.KEY_IMG_URLS, (ArrayList) icons);
//                startActivity(intent);
//                break;
            case R.id.tv_right: //更多
                if (statusList.size() > 0) {
                    if (pwMyPopWindow.isShowing()) {
                        pwMyPopWindow.dismiss();// 关闭
                    } else {
                        pwMyPopWindow.showAsDropDown(tvRight);// 显示
                    }
                }
                break;

        }
    }

    private void checkVin(){
        if (carDetails.getVin()!=null && !carDetails.getVin().equals(etVinCode.getText().toString().trim())){
            checkVinPresenter.checkvin();
        }else{
            taskDetailPresenter.UpData();
        }
    }

    class NetworkImageHolderView implements Holder<String> {
        private ImageView imageView;
        private TextView title;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            View view = LayoutInflater.from(context).inflate(R.layout.taskdetail_photo, null);
            imageView = (ImageView) view.findViewById(R.id.photo_img);
            title = (TextView) view.findViewById(R.id.title);
            return view;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            title.setText(titlePic.get(position));
            ImageLoader.getInstance().displayImage(data, imageView, appContext.options);
        }
    }


}
